import axios from 'axios'
import qs from "qs";
import encrypt from "@/util/encrypt.js";
import decrypt from "@/util/decrypt.js";
import router from '../router'
import cookie from "@/util/cookie.js";


const isProduction = !!(process.env.NODE_ENV === 'production')
let staticURL = isProduction ? 'http://localhost:8888' : 'http://localhost:8888';

axios.defaults.timeout = 5000;
//axios.defaults.baseURL = isProduction ? 'https://api.pandacr.cn' : 'http://localhost:8888';
// axios.defaults.baseURL = isProduction ? 'https://api.hdsgou.com' : 'https://api.hdsgou.com';// u20093
axios.defaults.baseURL = isProduction ? 'http://47.97.228.217' : 'http://47.97.228.217';// u20129
//axios.defaults.baseURL = isProduction ? 'https://api.pandacr.cn' : 'https://api.pandacr.cn';
//demo
//axios.defaults.baseURL = isProduction ? 'https://api.demo.jiangxinsc.com' : 'https://api.demo.jiangxinsc.com';



//http request 拦截器
axios.interceptors.request.use(
  config => {
		// const userId = localStorage.getItem('token')
		// const memberId = localStorage.getItem('memberId')
		// if (userId != null) {
		// 	if(config.data){
		// 		config.data.token = userId;
		// 	}else{
		// 		config.data = {token:userId}
		// 	}
		// }

		// if (memberId != null) {
		// 	if(config.data){
		// 		config.data.memberId = memberId;
		// 	}else{
		// 		config.data = {memberId:memberId}
		// 	}
		// }
    console.log('call url :',config.url);
    console.log('reqData:::',config.data)
    const reqData = encrypt(config.data);
    config.data = qs.stringify(reqData);
    config.responseType = 'text';
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

//响应拦截器即异常处理
axios.interceptors.response.use(response => {
  if(response != null){
    const respData = decrypt(response.data);
    let respJson = JSON.parse(respData);
    if(process.env.NODE_ENV!=='production'){
      console.log('respJson:::',respJson)
    }
    let respCode = respJson.code;
    // if(respCode!=0&&respCode!=401){
		// 	vm.$toast.fail(respJson.msg)
		// 	vm.$loading.close();
		// }else if(respCode == 401){
    //   console.log('req auth');
		// 	vm.$loading.close();
    //   router.push(
    //     { path: '/login' }
    //   );
    // }

    return respJson;
  }
}, err => {
  if (err && err.response) {
		console.log(err)
    switch (err.response.status) {
      case 400:
        console.log('错误请求')
        break;
      case 401:
        console.log('未授权，请重新登录')
        break;
      case 403:
        console.log('拒绝访问')
        break;
      case 404:
        console.log('请求错误,未找到该资源')
        break;
      case 405:
        console.log('请求方法未允许')
        break;
      case 408:
        console.log('请求超时')
        break;
      case 500:
        console.log('服务器端出错')
        break;
      case 501:
        console.log('网络未实现')
        break;
      case 502:
        console.log('网络错误')
        break;
      case 503:
        console.log('服务不可用')
        break;
      case 504:
        console.log('网络超时')
        break;
      case 505:
        console.log('http版本不支持该请求')
        break;
      default:
        console.log(`连接错误${err.response.status}`)
    }
  } else {
    console.log('连接到服务器失败')
  }
  return Promise.reject(err.response)
});


/**
 * 取消自定义的拦截器(一些特殊接口不需要经过全局拦截)
 */
export const axiosCancelResInterceptors = function () {
  const instance = axios.create();
  instance.interceptors.request.use( config => {
    const userId = localStorage.getItem('token')
    const memberId = localStorage.getItem('memberId')

    if (userId != null) {
      if(config.data){
        config.data.token = userId;
      }else{
        config.data = {token:userId}
      }
    }

    if (memberId != null) {
      if(config.data){
        config.data.memberId = memberId;
      }else{
        config.data = {memberId:memberId}
      }
    }

    console.log('reqData:::',config.data)
    const reqData = encrypt(config.data);
    config.data = qs.stringify(reqData);
    config.responseType = 'text';
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }
    return config;
  }, err => {
    return Promise.reject(err);
  });
  instance.interceptors.response.use(function (response) {
    if(process.env.NODE_ENV!=='production'){
      console.log('respJson:::',JSON.parse(decrypt(response.data)))
    }
    return Promise.resolve(JSON.parse(decrypt(response.data)))
  }, err => {
    return Promise.reject(err);
  });
  return instance
};


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
      .then(response => {
        resolve(response);
      })
      .catch(err => {
        reject(err)
      })
  })
};


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.post(url,data)
      .then(response => {
        resolve(response);
      },err => {
        reject(err)
      })
  })
};

